'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 邮件
 * @author sundbcn@gmail.com (sun debing)
 */
var _ = require('lodash');
var moment = require('moment');
var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var dataApi = require('../../../libs/dataApi');
var PlayerManager = require('../../../libs/playerManager');
var rewardService = require('../../../services/rewardService');
var rewardType = require('../../../consts/rewardType.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 设置邮件状态
 */
Handler.prototype.setMailStatus = function (msg, session, next) {
    var role_id = session.uid;
    var mail_id = msg.mail_id;
    if (!mail_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['mail', 'accrued'], cb);
            },
            function (cb) {
                var mail_model = player_manager.mail;
                var mail = mail_model.getMailById(mail_id);

                // 判断邮件是否存在
                if (!mail) {
                    return next(null, {
                        code: Code.MAIL_NOT_EXIST
                    });
                }

                mail_model.deleteMail(mail_id);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 获取邮件物品
 */
Handler.prototype.reward = function (msg, session, next) {
    var role_id = session.uid;
    var mail_id = msg.mail_id;
    if (!mail_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['mail', 'role', 'build', 'arena', 'soldier', 'bag', 'soldier', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var mail_model = player_manager.mail;

                var mail_item = mail_model.getMailById(mail_id);
                var module_type = mail_item.module_type;
                var operation_type = mail_item.operation_type;

                // 领取邮件奖励附件，并删除附件
                reward_list = mail_item.getAndRemoveAttach();
                if (!reward_list) {
                    return next(null, {
                        code: Code.MAIL_REWARD_NOT_EXIST
                    });
                }

                mail_model.deleteMail(mail_id);
                rewardService.addRewardListToRole(player_manager, reward_list, module_type, operation_type);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 一键领取所有邮件奖励
 */
Handler.prototype.allReward = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['mail', 'role', 'arena', 'build', 'bag', 'soldier', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var mail_model = player_manager.mail;
                var mail_list = mail_model.getMailList();

                var _pushToRewardList = function (rw_list) {
                    _.forEach(rw_list, function (reward_item) {
                        reward_list.push(reward_item);
                    });
                };

                for (var i = mail_list.length - 1; i >= 0; i--) {
                    var mail_item = mail_list[i];
                    var module_type = mail_item.module_type;
                    var operation_type = mail_item.module_type;

                    // 领取邮件奖励附件，并删除附件
                    var rw_list = mail_item.getAndRemoveAttach();
                    if (!reward_list) {
                        return next(null, {
                            code: Code.MAIL_REWARD_NOT_EXIST
                        });
                    }

                    mail_model.deleteMail(mail_item.mail_id);
                    rewardService.addRewardListToRole(player_manager, rw_list, module_type, operation_type);

                    _pushToRewardList(rw_list);
                }
                reward_list = _compose_rewardList(reward_list);

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 合并奖励列表
 */
var _compose_rewardList = function (reward_list) {
    var reward_map = {};
    var new_reward_list = [];
    _.each(reward_list, function (reward_item) {
        var reward_type = reward_item.reward_type;
        if (reward_type === rewardType.EQUIP || reward_type === rewardType.RANDOM_EQUIP) {
            new_reward_list.push(reward_item);
        } else {
            if (reward_map[reward_type]) {
                reward_map[reward_type].reward_num += reward_item.reward_num;
            } else {
                reward_map[reward_type] = reward_item;
            }
        }
    });
    _.forEach(reward_map, function (reward_item, key) {
        new_reward_list.push(reward_item);
    });
    return new_reward_list;
};
